package com.example.lenovo.asia5b.home.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.example.lenovo.asia5b.home.bean.AccountBean;
import com.example.lenovo.asia5b.home.bean.UserBean;
import com.example.lenovo.asia5b.ui.DownloadPicture;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.ui.MyHorizontalScrollView;
import com.example.lenovo.asia5b.ui.PublicDialog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.JsonTools2;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPrefereLoginUtils;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONObject;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import app.BaseActivity;
import app.MyApplication;
import fay.frame.ui.U;



/**
 * Created by lenovo on 2017/6/22.
 */

public class LoginActivity extends BaseActivity implements ICallBack,GoogleApiClient.OnConnectionFailedListener{
    public int RequestCode = 10 ;
    private EditText longinUserName;
    private EditText loginPassword;
    private LoadingDalog loadingDalog;
    private ProgressDialog dialog;
    String url="",name="",openid="",type="";
    private GoogleApiClient mGoogleApiClient;
    private static int RC_SIGN_IN=10001;
    private MyHorizontalScrollView holl_user ;
    private LinearLayout ll_lay;
    private  boolean isOnes = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();

        holl_user.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                holl_user.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!isOnes) {
                            addView();
                            isOnes = true;
                        }
                    }
                }, 300);
            }
        });

    }

    public void initView() {
        loadingDalog = new LoadingDalog(this);
        F.id(R.id.btn_change_information).clicked(this);
        F.id(R.id.public_title_name).text(getResources().getString(R.string.login));
        F.id(R.id.btn_immediately_on).clicked(this);
        F.id(R.id.txt_register).clicked(this);
        F.id(R.id.tv_forgot_password).clicked(this);
        F.id(R.id.tv_login_phone).clicked(this);



        F.id(R.id.login_from_facebook).clicked(this);//facebook登录
//        F.id(R.id.login_from_google).clicked(this);//谷歌登录
        F.id(R.id.login_from_wechat).clicked(this);//微信登录
        F.id(R.id.login_from_qq).clicked(this);//QQ登录
        F.id(R.id.login_from_sina).clicked(this);//新浪登录
        holl_user = (MyHorizontalScrollView)findViewById(R.id.holl_user);
        ll_lay = (LinearLayout)findViewById(R.id.ll_lay);
        longinUserName = findViewById(R.id.login_user_name);
        loginPassword = findViewById(R.id.login_password);


        SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_STANDARD);
        signInButton.setOnClickListener(this);


        MyHorizontalScrollView.ScrollViewListener dd = new MyHorizontalScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(MyHorizontalScrollView scrollView, int x, int y, int oldx, int oldy) {
                int scrollX = scrollView.getScrollX();
                //获取中间位置
                int width = scrollView.getWidth();
                //获取每个控件的宽度
                int scrollViewMeasuredWidth =ll_lay.getChildAt(0).getMeasuredWidth();
                scrollX = scrollX +scrollViewMeasuredWidth*2/3;
                //获取到哪个控件居中
                int id = scrollX/scrollViewMeasuredWidth;
                if (id < list.size()) {
                    longinUserName.setText(list.get(id).user_name);
                }

            }
        };
        holl_user.setScrollViewListener(dd);

        F.id(R.id.txt_yhm).clicked(this);
        F.id(R.id.txt_sjh).clicked(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.btn_immediately_on://登录
                login();
                break;
            case R.id.txt_register://注册
                intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_forgot_password://忘记密码
                intent = new Intent(LoginActivity.this,ForgotPasswordActivity.class);
                intent.putExtra("from","loginpassword");
                startActivity(intent);
                break;
            case R.id.login_from_facebook://facebook登录
//                U.Toast(this,"facebook登录");
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.FACEBOOK, authListener);
                break;
//            case R.id.login_from_google://谷歌登录
//                U.Toast(this,"谷歌登录");
//                break;
            case R.id.login_from_wechat://微信登录
//                U.Toast(this,"微信登录");
                //如果没有安装微信
                if (!UMShareAPI.get(LoginActivity.this).isInstall(this, SHARE_MEDIA.WEIXIN)) {
                    return;
                }
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                break;
            case R.id.login_from_qq://QQ登录
//                U.Toast(this,"QQ登录");
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
                break;
            case R.id.login_from_sina://新浪登录
                //判断是否授权成功
//                UMShareAPI.get(LoginActivity.this).isAuthorize(LoginActivity.this,SHARE_MEDIA.SINA);
                //退出登录
//                UMShareAPI.get(LoginActivity.this).deleteOauth(LoginActivity.this, SHARE_MEDIA.SINA, authListener);
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.SINA, authListener);
                //查看新浪的包名和签名
//                UmengTool.getSignature(LoginActivity.this);
                break;
            case R.id.tv_login_phone://验证码登录
                intent = new Intent(LoginActivity.this,LoginForPhoneActivity.class);
                startActivity(intent);
                break;
            case R.id.sign_in_button:
                if (mGoogleApiClient == null) {
                    GoogleSignInOptions gso = new GoogleSignInOptions
                            .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                            .requestEmail()
                            .requestId()
                            //签名前先屏蔽，因为导致登录失败，然后也会导致签名后goole登录失败
//                .            requestIdToken(getString(R.string.default_web_client_id))  //获取token
                            .requestProfile()
                            .build();

                    mGoogleApiClient = new GoogleApiClient
                            .Builder(this)
                            .enableAutoManage(this, this)/* FragmentActivity *//* OnConnectionFailedListener */
                            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                            .build();
                }
                signIn();
                break;
            case R.id.txt_yhm:
                F.id(R.id.txt_yhm).textColorId(R.color.wathet2);
                F.id(R.id.txt_sjh).textColorId(R.color.my_999);
                F.id(R.id.txt_86).visibility(View.GONE);
                longinUserName.setInputType(InputType.TYPE_CLASS_TEXT);
                sjh_name = longinUserName.getText().toString();
                sjh_pass = loginPassword.getText().toString();
                loginPassword.setText(yhm_pass);
                longinUserName.setText(yhm_name);
                longinUserName.setHint(getResources().getString(R.string.yhm));
                break;
            case R.id.txt_sjh:
                F.id(R.id.txt_yhm).textColorId(R.color.my_999);
                F.id(R.id.txt_sjh).textColorId(R.color.wathet2);
                F.id(R.id.txt_86).visibility(View.VISIBLE);
                longinUserName.setInputType(InputType.TYPE_CLASS_PHONE);
                yhm_name= longinUserName.getText().toString();
                yhm_pass = loginPassword.getText().toString();
                loginPassword.setText(sjh_pass);
                longinUserName.setText(sjh_name);
                longinUserName.setHint(getResources().getString(R.string.mobile_phone2));
                break;
            default:
                break;
        }
    }

    String yhm_name = "",sjh_name = "",yhm_pass ="",sjh_pass="";

    /**
     * 登录接口
     */
    private void login(){
        String md5_32 = null;
        try{
            String user_name = longinUserName.getText().toString().trim();
            if(TextUtils.isEmpty(user_name)){
                U.Toast(this,getResources().getString(R.string.yhmbnwk));
            }else{
                String password = loginPassword.getText().toString().trim();
                if(password.length() < 6){
                    U.Toast(this,getResources().getString(R.string.mmcdbxdy6));
                }else{
                    loadingDalog.show();
                    Date date = new Date();
                    String time = String.valueOf(date.getTime());

                    String[] sort = {"user_name"+user_name,"password"+password,"time"+time,"user_alias"+ MyApplication.registrationId};
                    String sortStr = Logic.sortToString(sort);
                    Log.e("key：",sortStr);
                    md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
                    Log.e("md5_32Key：",md5_32);
                    Map<String,String> parmaMap = new HashMap<String,String>();
                    parmaMap.put("user_name",user_name);
                    parmaMap.put("password",password);
                    parmaMap.put("user_alias",MyApplication.registrationId);
                    parmaMap.put("time",time);
                    parmaMap.put("sign",md5_32);

                    JsonTools.getJsonAll(this, Setting.LOGINFORUSERANDPWD,parmaMap,0);
                    //解决 状态码返回3导致跳转的情况
                    JsonTools2.setOne(true);
                }
            }
        }catch(Exception e){
            Log.e("Login_error：",e.getMessage());
        }

    }

    /**
     * 第三方登录
     */
    private void loginTwo(){
        loadingDalog.show();
        try{
            String phoneRUL = Setting.THIRD_LOGIN;
            Map<String,String> map = new HashMap<String,String>();
            map.put("uid",openid);
            map.put("third_user",name);
            map.put("third_type",type);
            map.put("user_alias",MyApplication.registrationId);
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            map.put("time",time);
            String[] sortStr = {"uid"+openid,"third_user"+name,"third_type"+type,"time"+time,"user_alias"+ MyApplication.registrationId};
            Log.e("参数为：：：：：：：：：",Logic.sortToString(sortStr));
            String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(Logic.sortToString(sortStr)));
            map.put("sign",md5);
            JsonTools.getJsonAll(this,phoneRUL,map,1);
            JsonTools2.setOne(true);
        }catch (Exception e){
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result = null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            try{
                if(result != null){
                    if(action == 0){
                        JSONObject jsonObject = (JSONObject)result;
                        int state = (int)jsonObject.getInt("State");
                        if(state == 0){
                            saveUser(jsonObject.getJSONObject("user"));
                        }else if(state == 1){
                            U.Toast(LoginActivity.this,getResources().getString(R.string.qmsb)
                            );
                        }else if(state == 2){
                            U.Toast(LoginActivity.this,getResources().getString(R.string.zhmmbnwk));
                        }else if(state == 3){
                            U.Toast(LoginActivity.this,getResources().getString(R.string.zhbcz));
                        }else if(state == 4){
                            U.Toast(LoginActivity.this,getResources().getString(R.string.mmcw));
                        }else if (state == 10) {
                            U.Toast(LoginActivity.this,getResources().getString(R.string.hqyc));
                        }
                        loadingDalog.dismiss();
                    }  else if(action == 1){
                        JSONObject jsonObject = (JSONObject)result;
                        Log.e("返回的数值：：：：：：：：：",jsonObject.toString());
                        int state = (int)jsonObject.getInt("State");
                        if(state == 0){
                            saveUserThr(jsonObject.getJSONObject("user"));
                        }else if(state == 1){
                            U.Toast(LoginActivity.this,getResources().getString(R.string.qmsb)
                            );
                        }else if(state == 2){
                            U.Toast(LoginActivity.this,getResources().getString(R.string.zhmmbnwk));
                        }else if(state == 3){
                            Intent intent = new Intent(LoginActivity.this,LoginForPhoneActivity.class);
                            intent.putExtra("url",url);
                            intent.putExtra("name",name);
                            intent.putExtra("openid",openid);
                            intent.putExtra("type",type);
                            startActivity(intent);
                        }else if (state == 10) {
                            U.Toast(LoginActivity.this,getResources().getString(R.string.hqyc));
                        }
                        loadingDalog.dismiss();
                    }

                }else{
                    U.Toast(LoginActivity.this,getResources().getString(R.string.dlsb));
                    loadingDalog.dismiss();
                }
            }catch (Exception e){
                Log.e("Login_api_error：",e.getMessage());
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    /**
     * 登陆保存用户信息
     * @param json
     */
    private void saveUser(JSONObject json){
        Intent intent = null;
        try {
            UserBean bean = (UserBean)Logic.getBeanToJSONObject(json,new UserBean());
            if(!TextUtils.isEmpty(bean.user_name) && !TextUtils.isEmpty(bean.mobile_phone)
                    && !TextUtils.isEmpty(bean.email)){
                SharedPreferencesUtils.setObjectToShare(bean,"user");
                intent = new Intent(this,MainActivity.class);
                if (getIntent().hasExtra("commodity")){
                    finish();
                } else {
                    startActivity(intent);
                    finishAll();
                }
            }else{
                intent = new Intent(this,UploadHeadPortraitActivity.class);
                if (bean.is_uname.equals("1")){
                    intent.putExtra("phone",bean.mobile_phone);
                    intent.putExtra("register", "register");
                }
                intent.putExtra("user_id",json.getString("user_id"));
                startActivity(intent);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 登陆保存用户信息
     * @param json
     */
    private void saveUserThr(JSONObject json){
        try {
            UserBean bean = (UserBean)Logic.getBeanToJSONObject(json,new UserBean());
            SharedPreferencesUtils.setObjectToShare(bean,"user");
            Intent intent = new Intent(this,MainActivity.class);
            startActivity(intent);
            finishAll();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            Intent intent = new Intent();
            intent.putExtra("222",2222);
            this.setResult(300, intent);
            finish();
            return false;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }
    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
            SocializeUtils.safeShowDialog(dialog);
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回f
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            if (data == null) {
                return;
            }
            SocializeUtils.safeCloseDialog(dialog);
            Set<String> set = data.keySet();
            Log.e("平台名称:", platform.toString());
            Log.e("状态码:", action+"");
            for (String string : set) {
                Log.e("msg",
                        "============================Map=========================");
                Log.e("msg", string + "::::" + data.get(string));
                String str = data.get(string);

                // 设置头像
                if (string.equals("iconurl")) {
                    url = str;
                }
                // 设置昵称
                if (string.equals("last_name")) {
                    name = str;
                }
                if (string.equals("openid")) {
                    openid = str;
                }


                //QQ和微信
                // 设置头像
                if (string.equals("profile_image_url")) {
                    url = str;
                }
                // 设置昵称
                if (string.equals("screen_name")) {
                    name = str;
                }
                if (string.equals("openid")) {
                    openid = str;
                }
                if(TextUtils.isEmpty(openid)) {
                    if (string.equals("uid")) {
                        openid = str;
                    }
                }
            }
            if (platform.toString().equals("QQ")) {
                type = "5";
            } else if (platform.toString().equals("WEIXIN")){
                type = "3";
            }else if (platform.toString().equals("SINA")){
                type = "6";
            }else if (platform.toString().equals("FACEBOOK")){
                type = "1";
            }
            loginTwo();
            //当授权成功后，就取消授权
            UMShareAPI.get(LoginActivity.this).deleteOauth(LoginActivity.this, platform, authListener);
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            SocializeUtils.safeCloseDialog(dialog);
//            Toast.makeText(LoginActivity.this, "失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
              U.Toast(LoginActivity.this, getResources().getString(R.string.dlsb));
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            SocializeUtils.safeCloseDialog(dialog);
//            Toast.makeText(LoginActivity.this, "取消了", Toast.LENGTH_LONG).show();
        }
    };

    /**
     * QQ与新浪不需要添加Activity，但需要在使用QQ分享或者授权的Activity中
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        //谷歌登录成功回调
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        UMShareAPI.get(this).onSaveInstanceState(outState);
    }

    //------------------------------------------------谷歌----------------------------------------------

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    /**
     * 退出
     */
    private void signOut() {
       Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
               new ResultCallback<Status>() {
                   @Override
                   public void onResult(@NonNull Status status) {

                   }
               });
    }


    private void handleSignInResult(GoogleSignInResult result){
        Log.i("robin", "handleSignInResult:" + result.isSuccess());
        if(result.isSuccess()){
            Log.e("robin", "成功");
            GoogleSignInAccount acct = result.getSignInAccount();
            if(acct!=null){
                Log.e("robin", "用户名是:" + acct.getDisplayName());
                Log.e("robin", "用户email是:" + acct.getEmail());
                Log.e("robin", "用户头像是:" + acct.getPhotoUrl());
                Log.e("robin", "用户Id是:" + acct.getId());//之后就可以更新UI了
                Log.e("robin", "用户IdToken是:" + acct.getIdToken());
//                U.Toast(LoginActivity.this,getResources().getString(R.string.cg));
//                U.Toast(LoginActivity.this,"用户名是:" + acct.getDisplayName()+"\n用户email是:" + acct.getEmail()+"\n用户头像是:" + acct.getPhotoUrl()+ "\n用户Id是:" + acct.getId()+"\n用户IdToken是:" + acct.getIdToken());
                // 设置头像
                if (null != acct.getPhotoUrl()) {
                    url = acct.getPhotoUrl().toString();
                }
                // 设置昵称
                name = acct.getDisplayName().toString();
                openid = acct.getId();
                type = "2";
                loginTwo();
                //登陆成功后就开始注销
                signOut();
            }
        }else{
            U.Toast(LoginActivity.this,getResources().getString(R.string.dlsb)+result.getStatus());
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(mGoogleApiClient!=null) mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mGoogleApiClient!=null&&mGoogleApiClient.isConnected()) {
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    //=============================================================用户头像============================================================================
    private  List<AccountBean> list;
    public void addView() {
        if (null == SharedPrefereLoginUtils.getBeanList()){
            return;
        }
         list = SharedPrefereLoginUtils.getBeanList();
        if (list.size() == 0) {
            return;
        }
        int width  = 0;
        if (list.size() < 2) {
            width = holl_user.getWidth() / list.size();
        } else {
            width = holl_user.getWidth() / 3;
            View hotSaleView =  LayoutInflater.from(LoginActivity.this).inflate(R.layout.item_login_hear, null);
            hotSaleView.setLayoutParams(new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT));
            ImageView image_hear =(ImageView)hotSaleView.findViewById(R.id.image_hear);
            image_hear.setVisibility(View.GONE);
            ll_lay.addView(hotSaleView);
        }
        for (int i =0; i < list.size();i++) {
            final AccountBean bean = list.get(i);
            View hotSaleView =  LayoutInflater.from(LoginActivity.this).inflate(R.layout.item_login_hear, null);
            hotSaleView.setLayoutParams(new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT));
            ImageView image_hear =(ImageView)hotSaleView.findViewById(R.id.image_hear);
            DownloadPicture.loadHearNetwork(bean.avatar,image_hear);
            final int id = i;
            image_hear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    longinUserName.setText(bean.user_name);
                    if (1 !=list.size()) {
                        setCurrentTab(id + 1);
                    }
                }
            });
            image_hear.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    isDeleteDialog(id);
                    return true;
                }
            });
            if (i == 0) {
                longinUserName.setText(bean.user_name);
            }
            ll_lay.addView(hotSaleView);
        }
        if (list.size() >= 2) {
            width =holl_user.getWidth() / 3;
            View hotSaleView =  LayoutInflater.from(LoginActivity.this).inflate(R.layout.item_login_hear, null);
            hotSaleView.setLayoutParams(new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT));
            ImageView image_hear =(ImageView)hotSaleView.findViewById(R.id.image_hear);
            image_hear.setVisibility(View.GONE);
            ll_lay.addView(hotSaleView);
        }
    }

    public void setCurrentTab(int position){
        View txt_name =ll_lay.getChildAt(position);
        //获取屏幕宽度
        int screenWidth=holl_user.getWidth();
        //计算控件居正中时距离左侧屏幕的距离
        int middleLeftPosition=(screenWidth-txt_name.getWidth())/2;
        //正中间位置需要向左偏移的距离
        int offset=txt_name.getLeft()-middleLeftPosition;
        //让水平的滚动视图按照执行的x的偏移量进行移动
        holl_user.smoothScrollTo(offset,0);
    }
    /**
     * 弹出删除消息
     */
    public void isDeleteDialog(final  int id) {
        if (list.size() == 1) {
            return;
        }
        final PublicDialog dialog = new PublicDialog(this);
        dialog.setTitle(getResources().getString(R.string.xtts));// 设置title
        dialog.setContent(getResources().getString(R.string.qdscdqzhm));// 设置内容
        dialog.setLeftButton(getResources().getString(R.string.qx));// 设置按钮
        dialog.setRightButton(getResources().getString(R.string.confirm));
        dialog.setLeftButtonVisible(true); // true显示 false隐藏
        dialog.setRightButtonVisible(true);// true显示 false隐藏
        dialog.setRightButtonClick(new PublicDialog.OnClickListener() {

            @Override
            public void onClick(View v) {
                //调用删除消息接口
                delView(id);
            }
        });
        dialog.setLeftButtonClick(new PublicDialog.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismissDialog();
            }
        });
        dialog.showDialog();
    }

    public void delView(int id) {
        list.remove(id);
        SharedPrefereLoginUtils.setObjectToShare(list,SharedPrefereLoginUtils.ACCOUNT_NAME);
        ll_lay.removeAllViews();
        addView();
        holl_user.smoothScrollTo(0,0);
    }
}
